package com.wangxinyuchuan.demo.singleton;

/**
 * 懒汉式
 * 虽然达到了按需初始化的目的，但是带来了线程不安全的问题
 */
public class Demo3 {

    private static Demo3 INSTANCE;

    private Demo3() {

    }

    public static Demo3 getInstance() {
        if (null == INSTANCE) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            INSTANCE = new Demo3();
            return INSTANCE;
        }
        return INSTANCE;
    }


    public static void main(String[] args) {
//        Demo3 a = Demo3.getInstance();
//        Demo3 b = Demo3.getInstance();
//        System.out.println(a == b);

        // 模拟多线程获取单例对象
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                System.out.println(Demo3.getInstance());
            }).start();
        }
    }
}
